﻿using NLog.Config;
using NLog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NLog.Layouts;
using NLog.Targets.Wrappers;
using NLog.Targets;

namespace RestartService
{
    public class NlogHelper : Logger
    {
        public Logger logger;
        public static LoggingConfiguration Configure { get; protected set; }

        public NlogHelper(LogLevel _logLevel, string target = "Logs", string format = "txt")
        {
            //Target  target;
            try
            {
                Configure = LogManager.Configuration ?? new LoggingConfiguration();

                FileTarget nlogTarget = new FileTarget();
                nlogTarget.Name = target;
                if (!string.IsNullOrEmpty(target))
                    nlogTarget.FileName = $"./{target}/" + "${shortdate}" + $".{format}";
                else
                    nlogTarget.FileName = $"./Logs/" + "${shortdate}" + $".{format}";
                nlogTarget.Layout = Layout.FromString("${longdate} [${level}]:  ${message}");

                //异步写入
                AsyncTargetWrapper wrapper = new AsyncTargetWrapper(nlogTarget);
                wrapper.Name = target;

                Configure.AddTarget(nlogTarget.Name, wrapper);

                Configure.LoggingRules.Add(new LoggingRule(target, _logLevel, wrapper) { Final = true });

                LogManager.Configuration = Configure;

                logger = LogManager.GetLogger(target);
            }
            catch (Exception ex) { }
        }

    }
}
